package com.example.controller;

import org.redisson.Redisson;
import org.redisson.RedissonRedLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/redlock")
public class RedLockController {

    @Autowired
    RedissonClient redissonClient;

    @RequestMapping("/lock")
    public void getLock() {
        long start = System.currentTimeMillis();
        RLock lock1 = redissonClient.getLock("lock1");
        RLock lock2 = redissonClient.getLock("lock2");
        RLock lock3 = redissonClient.getLock("lock3");
        RedissonRedLock redLock = new RedissonRedLock(lock1, lock2, lock3);
        lock1.lock(5,TimeUnit.SECONDS);
        lock2.lock(5,TimeUnit.SECONDS);
        try {

            /**
             * 4.尝试获取锁
             * redLock.tryLock((long)waitTimeout, (long)leaseTime, TimeUnit.SECONDS)
             * waitTimeout 尝试获取锁的最大等待时间，超过这个值，则认为获取锁失败
             * leaseTime   锁的持有时间,超过这个时间锁会自动失效（值应设置为大于业务处理的时间，确保在锁有效期内业务能处理完）
             */
            // 尝试加锁，最多等待100秒，上锁以后10秒自动解锁
            boolean res = redLock.tryLock(5, 3, TimeUnit.SECONDS);
            System.out.println(res);
            if (res) {
                //成功获得锁，在这里处理业务
                System.out.println("成功获取到锁...");
            }

        } catch (Exception e) {
            throw new RuntimeException("aquire lock fail");
        } finally {
            // 无论如何, 最后都要解锁
            redLock.unlock();
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
}
